package com.phkj.qdh.ui.fragment.instructionsheet

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.activity.OnBackPressedCallback
import androidx.core.content.ContextCompat
import androidx.fragment.app.commit
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.hjq.toast.ToastUtils
import com.phkj.qdh.R
import com.phkj.qdh.bean.InstructionBean
import com.phkj.qdh.databinding.FragmentInstructionSheetDetailBinding
import com.phkj.qdh.ui.adapter.ImagerViewAdapter
import com.phkj.qdh.ui.adapter.RelevantWarningInformationAdapter
import com.phkj.qdh.ui.adapter.ShenPiAdapter
import com.phkj.qdh.ui.dialog.CommonConfirmDialog
import com.phkj.qdh.ui.dialog.CommonConfirmListener
import com.phkj.qdh.utils.MyItemDecoration
import com.phkj.qdh.utils.gone
import com.phkj.qdh.utils.launchAndRepeatWithViewLifecycle
import com.phkj.qdh.utils.visible
import kotlinx.coroutines.flow.collectLatest

private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"

/**
 * 指令单详情
 */
class InstructionSheetDetailFragment : Fragment() {
    private var param1: InstructionBean? = null
    private var param2: String? = null
    private var _binding: FragmentInstructionSheetDetailBinding? = null
    private val binding get() = _binding!!
    private val iVAdapter by lazy { ImagerViewAdapter(true) }
    private val shenPiAdapter by lazy { ShenPiAdapter() }
    private val relevantWarningInformationAdapter by lazy { RelevantWarningInformationAdapter() }
    private lateinit var vm: InstructionVM
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {
            param1 = it.getParcelable(ARG_PARAM1)
            param2 = it.getString(ARG_PARAM2)
        }
        requireActivity().onBackPressedDispatcher.addCallback(this,
            object : OnBackPressedCallback(true) {
                override fun handleOnBackPressed() {
                    parentFragmentManager.popBackStack()
                }
            })
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View? {
        _binding = FragmentInstructionSheetDetailBinding.inflate(inflater, container, false)
        vm = ViewModelProvider(this, getInstructionVMProvider())[InstructionVM::class.java]
        return binding.root
    }


    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        binding.run {
            ivBack.setOnClickListener {
                parentFragmentManager.popBackStack()
            }
            rvLawSubmit.run {
                layoutManager =
                    LinearLayoutManager(requireContext(), RecyclerView.HORIZONTAL, false)
                adapter = iVAdapter
                addItemDecoration(
                    MyItemDecoration(
                        ContextCompat.getColor(
                            requireContext(), R.color.transparent
                        ), 25, RecyclerView.HORIZONTAL
                    )
                )
            }
            rvShenpi.run {
                layoutManager = LinearLayoutManager(requireContext())
                adapter = shenPiAdapter
            }
            rv.run {
                layoutManager = LinearLayoutManager(requireContext())
                adapter = relevantWarningInformationAdapter
            }
            tvNo.setOnClickListener {
                val dialog = CommonConfirmDialog.getInstance("驳回", "确定要驳回吗")
                dialog.setCancelListener(object : CommonConfirmListener {
                    override fun dOk() {
                        vm.getInstructionReject(param1?.id!!)
                    }

                    override fun dCancel() {
                    }

                })
                dialog.show(parentFragmentManager, "")
            }
            btnOk.setOnClickListener {
                parentFragmentManager.commit {
                    addToBackStack("detail")
                    replace(id, InstructionSheetHandleFragment.newInstance(param1!!, ""))
                    setReorderingAllowed(true)
                }
            }

        }
        relevantWarningInformationAdapter.setOnItemClickListener { adapter, _, pos ->
            adapter.getItem(pos)?.let {
                parentFragmentManager.commit {
                    addToBackStack("jinqgingdetail")
                    replace(id, RelevantWarningInformationFragment.newInstance(it, ""))
                    setReorderingAllowed(true)
                }
            }

        }


        launchAndRepeatWithViewLifecycle {
            vm.instructionRejectResult.collectLatest {
                if (it) {
                    parentFragmentManager.popBackStack()
                }
            }
        }
        launchAndRepeatWithViewLifecycle {
            vm.instructionDetail.collectLatest {
                binding.tvContent.text = it.policeSituationContent
                iVAdapter.submitList(it.picUrls)
                relevantWarningInformationAdapter.submitList(it.policeSituationLinkIds)
                if (it.correctiveFeedbackVOList.isNullOrEmpty()) {
                    binding.spShenpi.gone()
                    binding.rvShenpi.gone()
                    binding.tvShenpi.gone()
                    binding.tvNo.visible()
                } else {
                    binding.spShenpi.visible()
                    binding.rvShenpi.visible()
                    binding.tvShenpi.visible()
                    binding.tvNo.gone()
                    shenPiAdapter.submitList(it.correctiveFeedbackVOList)
                }
                when (it.status) {
                    1, 2 -> {
                        binding.tvNo.visible()
                        binding.btnOk.visible()
                    }
                    3 -> {
                        binding.tvNo.gone()
                        binding.btnOk.visible()
                    }

                    4 -> {//已驳回
                        binding.tvNo.visible()
                        binding.btnOk.visible()
                    }

                    5 -> {
                        binding.tvNo.gone()
                        binding.btnOk.visible()
                    }

                    6, 7 -> {/// 已完成
                        binding.tvNo.gone()
                        binding.btnOk.gone()
                    }
                    else -> {

                    }
                }
                if (it.status == 1) {

                } else {

                }
            }
        }
        vm.getInstructionDetail(map = hashMapOf<String, Any?>("instructionId" to param1?.id))
//        vm.getInstructionDetail(map = hashMapOf<String, Any?>("instructionId" to 79))
    }

    companion object {
        @JvmStatic
        fun newInstance(param1: InstructionBean, param2: String) =
            InstructionSheetDetailFragment().apply {
                arguments = Bundle().apply {
                    putParcelable(ARG_PARAM1, param1)
                    putString(ARG_PARAM2, param2)
                }
            }
    }
}